package com.baidu.structure.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.baidu.structure.BaseActivity;
import com.baidu.structure.R;
import com.baidu.structure.adapter.AddContactAdapter;
import com.baidu.structure.bean.ContactBean;
import com.baidu.structure.utils.LogUtils;
import com.baidu.structure.utils.ThreadPoolUtils;
import com.baidu.structure.utils.ToastUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

import java.util.ArrayList;
import java.util.TimerTask;

/**
 * A login screen that offers login via email/password.
 */
public class AddContactActivity extends BaseActivity implements AddContactAdapter.OnAddClickListener {
    private final String TAG=AddContactActivity.class.getSimpleName();
    private RecyclerView contactList;
    private EditText queryView;
    private ImageButton clearButton;
    private ArrayList<ContactBean> itemData;
    private AddContactAdapter adapter;

    public static final int ADD_SUCCESS = 51;
    public static final int ADD_FAILURE = 50;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        init();
    }

    private void init() {
        this.contactList = (RecyclerView) findViewById(R.id.contact_list);
        queryView = (EditText) findViewById(R.id.query);
        clearButton = (ImageButton) findViewById(R.id.search_clear);

        itemData = new ArrayList<>();
        adapter = new AddContactAdapter(itemData, this);
        contactList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        contactList.setAdapter(adapter);
        adapter.setOnAddClickListener(this);

        queryView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0)
                    clearButton.setVisibility(View.VISIBLE);
                else
                    clearButton.setVisibility(View.INVISIBLE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        queryView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                LogUtils.e(TAG,"----"+actionId);
                if (actionId == EditorInfo.IME_ACTION_NEXT) {
                    hideSoftKeyboard();
                    searching();
                }
                return false;
            }
        });
        clearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                queryView.setText("");
            }
        });

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case ADD_SUCCESS:
                        AddContactActivity.this.finish();
                        break;
                    case ADD_FAILURE:
                        ToastUtils.simpleToast(AddContactActivity.this,getString(R.string.toast_add_contact_failure));
                        break;
                }
            }
        };
    }

    //search
    private void searching() {
        itemData.clear();
        itemData.add(new ContactBean(R.mipmap.icon_haizei, queryView.getText().toString()));
        adapter.notifyDataSetChanged();
    }

    protected void hideSoftKeyboard() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onAddClick(final int position) {
        LogUtils.e(TAG,"---p="+position);
        ThreadPoolUtils.execute(new TimerTask() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().contactManager().addContact(itemData.get(position).getName(), getString(R.string.info_add_contact));
                    mHandler.sendEmptyMessage(ADD_SUCCESS);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    mHandler.sendEmptyMessage(ADD_FAILURE);
                }
            }
        });
    }
}

